<?php
session_start();
error_reporting('E_ALL');
$self = $_SERVER['PHP_SELF'];

include 'functions.php';
include '../db-control/inc/functions.php';
include '../db-control/dbOrganization.php';
include '../model/Organization.php';
include '../db-control/dbContact.php';
include 'Messagebox.php';

if (!isLoggedIn()) {
   die("Please log in <a href='../'>HERE</a> first.");
}

if (!isManager()) {
   die("<a href='javascript:history.go(-1);'><<< Go Back - You are not authorized to view this page...</a>");
}

$message = saveItems();

$page = $_REQUEST['view'];
goToPage($page);
?>
<!DOCTYPE html>
<html>
   <head>
      <title>Admin | Organizations</title>
      <link rel="stylesheet" type="text/css" href="../css/style.css" />
      <script type="text/javascript">
         function updateSearchField(){
            var val = search_form.elements["searchFor"].value;
            search_form.search.placeholder = val;
         }
         function submit(){
            document.forms["view_dropdown"].submit();
         }
      </script>
      <style type="text/css">
         textarea.edit{
            width:175px;
            height:50px;
            resize:none;
         }   
      </style>
   </head>
   <body>
      <form action="<?php echo $self; ?>" method="get">
         <table width="100%">
            <div align="left">
               <tr><td rowspan="7" valign="top"><img alt="" src="../img/unhmlogo.png" width="200px" height="120px" /></td></tr>
               <tr><td align="right" valign="top"><a href="../logout.php" title="Logout of the system.">Logout</a> | <a href="../help.php" title="View the help documentation.">?</a></td></tr>
               <tr><td width="100%" align="left"><h3 style="font-size:2em;">Internship 2 Career</h3><br /></td></tr>
               <tr><td align="left"><p>You can filter your searches by category, city, or a custom search:</p></td></tr>
               <tr>
                  <td align="left">
                     <form action="<?php echo $self; ?>" method="post" id="view_dropdown">
                        <font size="5">Manage:</font>
                        <?php
                        viewDropDown('organizations');
                        ?>
                     </form>
                     <hr />
                  </td>
               </tr>
               <tr>
                  <td align="left">
                  </td>
               </tr>
               <tr>
                  <td align="left">
                     <form action="<?php echo $self; ?>" method="get" id="search_form">
                        <?php
                        searchBox();
                        ?>
                     </form>
                  </td>
               </tr>
               <tr>
                  <td></td><td align="left"><?php ?></td>
               </tr>
            </div>
         </table>
         <table width="100%">
            <tr>
               <td valign="top" width="20%">
                  <?php editForm($message); ?>
               </td>
               <td width="5%"></td>
               <td width="75%">
                  <?php include 'organization_list.php'; ?>
               </td>
            </tr>
         </table>


      </form>
      <br /><br />

   </body>
</html>


<?php

function saveItems() {
   if (isset($_POST['save_new'])) {
      //user is trying to save a new organization
      return saveOrganization();
   }
   $id = $_POST['organization_id'];
   if ($id == '') {
      //check to see if creating new organization
      if ($_GET['action'] == 'new' || $_GET['action'] == 'edit') {
         $message['message'] = "";
         return $message;
      } else {
         $message['message'] = "Please select an organization to edit.";
         return $message;
      }
   }
   if (isset($_POST['edit_delete'])) {
      //user wants to delete the current opportunity
      if (!dbOrganization::deleteFromOrganization($id)) {
         $message['message'] = "Feature not enabled right now...";
         $message['error'] = true;
      } else {
         $message['message'] = "Deleted organization successfully!";
      }
      return $message;
   } else if (isset($_POST['edit_save'])) {
      //user is trying to save the opportunity details
      $name = $_POST['edit_name'];
      $address1 = $_POST['edit_address1'];
      $address2 = $_POST['edit_address2'];
      $city = $_POST['edit_city'];
      $state = $_POST['edit_state'];
      $zip = $_POST['edit_zip'];
      $desc = $_POST['edit_desc'];

      $o = new Organization($name, $desc, $address1, $address2, $city, $state, $zip);
      if (!dbOrganization::updateOrganization($id, $o)) {
         $message['message'] = "There was an error saving the organization.";
         $message['error'] = true;
      } else {
         $message['message'] = "Organization saved successfully!";
      }
      return $message;
   }
}

function saveOrganization() {
   //check fields filled in
   if ($_POST['edit_name'] == '' || $_POST['edit_address1'] == '' || $_POST['edit_city'] == '' ||
           $_POST['edit_state'] == '' || $_POST['edit_zip'] == '') {
      //something is missing
      $result['message'] = "Please fill in all the fields.";
      $result['error'] = true;
   } else {
      //add organization to the database
      $o = new Organization($_POST['edit_name'], $_POST['edit_desc'], $_POST['edit_address1'], $_POST['edit_address2'], $_POST['edit_city'], $_POST['edit_state'], $_POST['edit_zip']);
      $success = dbOrganization::addOrganization($o);
      if (!$success) {
         $result['message'] = "ERROR: Could not add organization.";
         $result['error'] = true;
      } else {
         $result['message'] = "Added organization to the database!";
         $result['error'] = false;
      }
   }
   return $result;
}

function editForm($message) {
   //get the organization ID
   $orgID = $_POST['organization_id'];

   if (isset($_GET['action'])) {
      //user is coming from the internships page;
      if ($_GET['action'] == 'edit') {
         //user is trying to edit an organization with ID.........
         $orgID = $_GET['orgID'];
         dbOrganization::getAllByID($orgID, $org);
      }
   }

   if ($orgID != null) {
      //get the information associated with that ID
      dbOrganization::getAllByID($orgID, $org);
   }
   $self = $_SERVER['PHP_SELF'];

   //fill in the forms
   if (isset($_POST['save_new']) && $message['error'] == true) {
      //user has tried to save, but there was an error
      $orgName = $_POST['edit_name'];
      $address1 = $_POST['edit_address1'];
      $address2 = $_POST['edit_address2'];
      $city = $_POST['edit_city'];
      $state = $_POST['edit_state'];
      $zip = $_POST['edit_zip'];
      $desc = $_POST['edit_desc'];
   } else {
      $orgName = $org['organizationName'];
      $address1 = $org['address'];
      $address2 = $org['address1'];
      $city = $org['city'];
      $state = $org['stateName'];
      $zip = $org['zip'];
      $desc = $org['description'];
   }
   echo "<form action='$self' method='post'>";
   echo "<input type='hidden' name='organization_id' value='$orgID' />";
   echo "<table>";
   echo "<tr><td colspan='2'><a href='organizations.php?action=new'>Add new organization...</a></td></tr>";
   echo "<tr><td colspan='2'><p class='error'>{$message['message']}</p></td></tr>";
   echo "<tr><td align='right'>Name:</td><td><input type='text' value='$orgName' name='edit_name' /></td></tr>";
   echo "<tr><td align='right'>Address 1:</td><td><input type='text' value='$address1' name='edit_address1' /></td></tr>";
   echo "<tr><td align='right'>Address 2:</td><td><input type='text' value='$address2' name='edit_address2' /></td></tr>";
   echo "<tr><td align='right'>City:</td><td><input type='text' value='$city' name='edit_city' /></td></tr>";
   echo "<tr><td align='right'>State:</td><td><input type='text' value='$state' name='edit_state' /></td></tr>";
   echo "<tr><td align='right'>Zip:</td><td><input type='text' value='$zip' name='edit_zip' /></td></tr>";
   echo "<tr><td valign='top' align='right'>Description:</td><td><textarea class='edit' name='edit_desc'>$desc</textarea></td></tr>";
   echo "<tr>";
   if (isAdmin() && !isset($_POST['save_new']) && $_GET['action'] != 'new') {
      echo "<td align='right'><input style='width:60px;' name='edit_delete' type='submit' value='Delete' /></td>";
   } else {
      echo "<td></td>";
   }
   if ($_GET['action'] == 'new' || isset($_POST['save_new'])) {
      echo "<td align='right'><input style='width:150px;' name='save_new' type='submit' value='Add' /></td></tr>";
   } else {
      echo "<td align='right'><input style='width:150px;' name='edit_save' type='submit' value='Save' /></td></tr>";
   }
   echo "</table>";
   echo "</form>";
}

function searchBox() {
   if (isset($_REQUEST['search'])) {
      $val = $_REQUEST['search'];
      $_SESSION['search'] = $val;
   } else {
      $val = $_SESSION['search'];
   }
   echo "Search: <input type='search' title='Search for a specific organization' name='search' onblur='this.form.submit();' value='$val'/>";
}

/**
 * @desc Displays a select box for categories
 * @param string $name
 */
function categoryDropDown() {
   include '../db-control/dbCategory.php';
   $result = dbCategory::getAllCategories();
   if (isset($_REQUEST['categoryChange'])) {
      $catName = $_REQUEST['categoryChange'];
      $_SESSION['category'] = $catName;
   } else {
      $catName = $_SESSION['category'];
   }
   $numRows = mysql_num_rows($result);

   echo "<form action='$self' method='post'>";
   echo "Category: <select title='Select a category to only show internships in that category.' onchange='this.form.submit()' name='categoryChange'>";
   if ($catName == '') {
      echo "<option SELECTED value=''>Select a category...</option>";
   } else {
      echo "<option value=''>Show All</option>";
   }
   for ($i = 0; $i < $numRows; $i++) {
      $row = mysql_fetch_assoc($result);
      $name = $row['categoryName'];
      if ($row['categoryName'] == $catName) {
         echo "<option SELECTED value='$name'>$name</option>";
      } else {
         echo "<option value='$name'>$name</option>";
      }
   }
   echo "</select>";
   echo "</form>";
}

function cityDropDown() {
   include '../db-control/dbOrganization.php';
   $result = dbOrganization::getCities();
   if (isset($_REQUEST['cityChange'])) {
      $city = $_REQUEST['cityChange'];
      $_SESSION['city'] = $city;
   } else {
      $city = $_SESSION['city'];
   }

   $numRows = mysql_num_rows($result);
   echo "<form action='$self' method='get'>";
   echo "City: <select title='Select a city to filter internships by that location.' onchange='this.form.submit()' name='cityChange'>";
   if ($city == null) {
      echo "<option value=''>Select a city...</option>";
   } else {
      echo "<option value=''>Show All</option>";
   }
   for ($i = 0; $i < $numRows; $i++) {
      $row = mysql_fetch_assoc($result);
      if (strcmp($row['city'], $city) == 0) {
         echo "<option SELECTED value='" . $row['city'] . "'>" . $row['city'] . "</option>";
      } else {
         echo "<option value='" . $row['city'] . "'>" . $row['city'] . "</option>";
      }
   }
   echo "</select>";
   echo "</form>";
}
?>
